<?php
declare(strict_types=1);

namespace app\index\controller\api;

use \Swoole\Http\Request;
use \Swoole\Http\Response;

use sys\Config;

class User {
    public \lib\User $user;
    public string $token;
    
    public $middleware = [
        \lib\middleware\NetbarAuth::class=>[
            'except'=>['login'=>true]
        ]
    ];

    const   MAX_RETRY_TIMES     = 5;
    const   MAX_LOCK_TIME       = 300;

    public function login(Request $request, Response $response)
    {
        $time = time();
        $data = json_decode($request->getContent(), true);
        $check = validate([
            'username'=>'require|length:2,32|nospace',
            'password'=>'require|length:3,32|nospace',
        ], __CLASS__.".".__LINE__)->check($data);
        if(!$check->pass()) return $check->jsonSerialize();

        $db = new \sys\Db();
        if(null !== ($userRc = $db->table('el_user')->where([['username','=', $data['username']]])->field([
            'id','username','nickname','mid','avatar','password','trytimes','lastlogin'
        ])->find())){
            if($userRc['trytimes'] >= static::MAX_RETRY_TIMES) {
                if(static::MAX_LOCK_TIME + $userRc['lastlogin'] > $time){
                    return ['success'=>false,'message'=>'您的账号被暂时锁定.'];
                }
            }
            
            if($userRc['password'] !== \mexti\Crypto::sm3($data['password'])){
                $db->table('el_user')->where([['id','=', $userRc['id']]])->inc('trytimes', 1)->update(['lastlogin'=>$time]);
                $limit = static::MAX_RETRY_TIMES - $userRc['trytimes'];
                return ['success'=>false,'message'=>$limit>0?"账号或密码错误, 重试{$limit}次后将被暂时锁定.":'密码错误,请稍后再试!'];
            }

            $db->table('el_user')->where([['id','=', $userRc['id']]])->update(['lastlogin'=>$time, 'trytimes'=>0]);

            if(!$userRc['avatar']) $userRc['avatar'] = '/test/blank.png';

            $user = ['logined'=>true];

            $need_fields = ['id', 'username', 'nickname', 'mid', 'avatar'];
            foreach($need_fields as $key){
                $user[$key] = $userRc[$key];
            }

            if(null === ($role = $db->table('el_user_role')->where(['uid','=', $user['id']])->find())){
                return ['success'=>false,'message'=>'抱歉, 您没有权限登录该平台.'];
            }

            $user['roles'] = $role['roles'];
            $user['role_id'] = $role['role_id'];
            $user['mid'] = $mid = $role['mid'];
            $user['token'] = $token = uniqueid();

            
            $merchant = \lib\Merchant::get($mid);
            $user['prod'] = $merchant->prod;
            $user['sid'] = $merchant->sid;

            $db->table('el_token')->insert([
                'token'         => $token,
                'uid'           => $user['id'],
                'plat_id'       => 0,
                'auth'          => [
                    ...$user
                ],
                'ip'            => $request->header['x-real-ip'] ?? $request->server['remote_addr'],
                'os'            => getos($request->header),
                'create_time'   => $time,
                'update_time'   => $time,
            ]);

            if($user['sid'] == \app\index\BootStarup::$sid){
                new \lib\LoginTokens($token, new \lib\User($user));
            }
            
            return ['success'=>true,'auth'=>$user];
        }

        return ['success'=>false,'message'=>'账号不存在.'];
    }

    public function logout(Request $request, Response $response)
    {
        if(null !== ($token = \lib\LoginTokens::get($this->token))){
            $token->logout();
            return ['success'=>true];
        }
        return ['success'=>false];
    }

}